{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "导包"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import jieba\n",
    "import numpy\n",
    "import pandas as pd\n",
    "from sklearn.feature_extraction.text import TfidfVectorizer\n",
    "from sklearn.naive_bayes import GaussianNB\n",
    "from sklearn.naive_bayes import MultinomialNB\n",
    "from sklearn.naive_bayes import BernoulliNB\n",
    "from sklearn import metrics"
   ]
  },
  {
   "cell_type": "markdown",
   "source": [
    "编写辅助函数用于读取文本文件内容"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "def loadfile(filepath,leibie):\n",
    "    '''加载文件内容和标签'''\n",
    "    filelist = os.listdir(filepath)\n",
    "    content = []\n",
    "    label = []\n",
    "\n",
    "    for file in filelist:\n",
    "        with open(filepath+\"/\"+file,encoding='gb18030')as f:\n",
    "            content.append(\"\".join(jieba.cut(f.read())))\n",
    "            label.append(leibie)\n",
    "    return content,label"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "获取数据"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "wenbendir = ['train','test']\n",
    "currentdir = os.getcwd()\n",
    "traincontent = []\n",
    "trainlabel = []\n",
    "testcontent = []\n",
    "testlabel = []\n",
    "for wenben in wenbendir:#['train','test']\n",
    "#     os.chdir(wenben)\n",
    "    wenbenlist = os.listdir(wenben)#【女性，体育，文学，校园】\n",
    "    for leibie in wenbenlist:\n",
    "        content,label=loadfile(wenben+\"/\"+leibie,leibie)\n",
    "        if wenben==\"train\":\n",
    "            traincontent += content\n",
    "            trainlabel +=label\n",
    "        elif wenben=='test':\n",
    "            testcontent += content\n",
    "            testlabel +=label\n",
    "        os.chdir(currentdir)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "加载停用词"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "with open('C:\\\\Users\\\\15775\\\\Desktop\\\\nlp\\\\stopwords\\\\cn_stopwords.txt',encoding='utf-8')as file:\n",
    "    stopwords = file.read().split(\"\\n\")\n",
    "stopwords"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "计算文本特征值"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "tfidf = TfidfVectorizer(stop_words=stopwords,max_df=0.5)\n",
    "traindata = tfidf.fit_transform(traincontent)\n",
    "testdata = tfidf.transform(testcontent)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "训练模型与测试"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "#多项式朴素贝叶斯\n",
    "nb_model = MultinomialNB(alpha=0.001)\n",
    "nb_model.fit(traindata,trainlabel)\n",
    "predict_test = nb_model.predict(testdata)\n",
    "print(\"多项式朴素贝叶斯文本分类的准确率为：\",metrics.accuracy_score(predict_test,testlabel))"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "#bernoulli朴素贝叶斯\n",
    "from sklearn.naive_bayes import BernoulliNB\n",
    "ber_model = BernoulliNB(alpha=0.001)\n",
    "ber_model.fit(traindata,trainlabel)\n",
    "ber_predict = ber_model.predict(testdata)\n",
    "print(\"bernoulli贝叶斯文本分类的准确率为：\",metrics.accuracy_score(ber_predict,testlabel))"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "#高斯贝叶斯分类器\n",
    "gauss_model = GaussianNB()\n",
    "gauss_model.fit(traindata.toarray(),trainlabel)\n",
    "gauss_predict = ber_model.predict(testdata.toarray())\n",
    "print(\"GaussianNB贝叶斯文本分类的准确率为：\",metrics.accuracy_score(gauss_predict,testlabel))\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}